/*- coding = utf-8 -*-
@Time : 2022/9/21 11:45
@Author : 管茂良
@File : request.tsx
@web  : www.php-china.com
@Software: WebStorm
*/
import baseConfig from "@/utils/config"
import {getToken} from "@/utils/storage";
import UploadFileSuccessCallbackResult = UniNamespace.UploadFileSuccessCallbackResult;
import GeneralCallbackResult = UniNamespace.GeneralCallbackResult;

type methodsType = 'GET' | 'POST' | 'PUT'
//普通请求 上传图片
type requestTypeType = 'ordinaryRequest' | 'uploadImg'

const request = (config:{methods:methodsType,url:string,data?:any,headers?:object,requestType?:requestTypeType})=>{
    let {methods,data,url,requestType} = config
    if(!requestType){
        requestType = "ordinaryRequest"
    }
    let TOKEN = getToken();
    if(TOKEN){
        config.headers={
            'X-CSRF-TOKEN' : `${TOKEN}`,
            'Authorization' : `token`,
            'content-type' : "application/x-www-form-urlencoded"
        }
    }
    config.headers = {
        'content-type' : "application/x-www-form-urlencoded"
    }
    //普通请求
    if(requestType == "ordinaryRequest"){
        return new Promise((resolve,reject)=>{
            uni.request({
                method:methods,
                url: baseConfig.BaseURL + url,
                data,
                header:config.headers,
                dataType: 'json',
                sslVerify: false,
                success: (res:any)=>{
                    resolve(res)
                },
                fail: (res:any)=>{
                    reject(res)
                },
            })
        })
    }else if( requestType == "uploadImg"){//上传图片
        return new Promise((resolve,reject)=>{
            uni.uploadFile({
                url: baseConfig.BaseURL + url,
                filePath: data.filePath,//要上传文件资源的路径
                name: data.file?data.file:'file',//文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
                formData: {
                    ...data
                },
                header:config.headers,
                success: (res:UploadFileSuccessCallbackResult)=>{
                    resolve(res)
                },
                fail: (res:GeneralCallbackResult)=>{
                    reject(res)
                },
            });
        })
    }
    return new Promise((resolve,reject)=>{
        reject("匹配不到正确请求类型")
    })
}

export {request}